/**
 * 
 */
package fachkonzept;

import java.util.Arrays;
import java.util.concurrent.ExecutionException;

import util.Car;
import datenhaltung.IDatenhaltung;


/**
 * @author Sebastian
 * manages the deleting transactions ordered by the carResultManager
 * and is able to restore the last erased car
 */
public class ReversableCarDeleter implements ICarDeleter {

	IDatenhaltung dataSource;
	Car lastDeletedCar;
	/**
	 * create a new <code>ReversableCarDeleter</code>
	 */
	ReversableCarDeleter() {
		// TODO Auto-generated constructor stub
	}
	/**
	 * create a new <code>ReversableCarDeleter</code>
	 * @param dataSource the data source
	 */
	ReversableCarDeleter(IDatenhaltung dataSource){
		
		this.dataSource = dataSource;
	}
	/**
	 * @return the dataSource
	 */
	IDatenhaltung getDataSource() {
		return dataSource;
	}
	/**
	 * @param dataSource the dataSource to set
	 */
	void setDataSource(IDatenhaltung dataSource) {
		this.dataSource = dataSource;
	}
	/**
	 * @return the lastDeletedCar
	 */
	Car getLastDeletedCar() {
		return lastDeletedCar;
	}
	/**
	 * @param lastDeletedCar the lastDeletedCar to set
	 */
	void setLastDeletedCar(Car lastDeletedCar) {
		this.lastDeletedCar = lastDeletedCar;
	}
	/* (non-Javadoc)
	 * @see fachkonzept.IDeleter#deleteCar(java.lang.String)
	 * @param identificationNumber cars' identification number
	 */
	@Override
	public void deleteCar(String identificationNumber)
			throws ExecutionException {
		
		Car carToStoreCondition = new Car();
		carToStoreCondition.setIdentificationNumber(identificationNumber);
		Car[] searchResultArray = dataSource.getCars(carToStoreCondition);
		if(searchResultArray!=null && searchResultArray.length != 0){
			
			lastDeletedCar = searchResultArray[0];
			dataSource.deleteCar(identificationNumber);
		}
	}
	/**
	 * makes the last erase undone and undeletes the last deleted car
	 */
	void undoLastDelete() throws ExecutionException{
		
		if(lastDeletedCar!=null) {
			
			Car searchConditions = new Car();
			searchConditions.setIdentificationNumber(lastDeletedCar.getIdentificationNumber());
			Car[] searchResultArray = dataSource.getCars(searchConditions);
			if(searchResultArray==null){
			
				dataSource.saveCar(lastDeletedCar);
			}
		}
	}
}
